<template>
<div>
		<el-form size="small" :model="form" :rules="rules" ref="ruleForm" label-width="100px">
			<el-form-item :label="$t('plus.checkin_activity')" prop="isOpen">
				<el-radio v-model="form.isOpen" :label="true">{{$t('plus.enable')}}</el-radio>
				<el-radio v-model="form.isOpen" :label="false">{{$t('plus.disable')}}</el-radio>
			</el-form-item>
			<div class="open-sign">
				<span class="gray9">{{$t('plus.checkin_enabled_note')}}</span>
			</div>
			<el-form-item :label="$t('plus.checkin_mode')" prop="signType">
				<el-radio v-model="form.signType" :label="0">{{$t('plus.mode_unlimited')}}</el-radio>
				<el-radio v-model="form.signType" :label="1">{{$t('plus.mode_weekly')}}</el-radio>
				<el-radio v-model="form.signType" :label="2">{{$t('plus.mode_monthly')}}</el-radio>
			</el-form-item>
			<div class="open-sign">
				<span class="gray9">{{$t('plus.mode_description')}}</span>
			</div>
			<div v-if="form.isOpen" class="mt16">
				<el-form-item :label="$t('plus.daily_checkin')" prop="everSign">
					<div class="d-s-s d-c bg_coupon">
						<el-form-item :label="$t('plus.give_coupon')">
							<el-radio-group v-model="form.isCoupon">
								<el-radio :label="true">{{$t('plus.enable')}}</el-radio>
								<el-radio :label="false">{{$t('plus.disable')}}</el-radio>
							</el-radio-group>
						</el-form-item>
						<div style="width: 96%" v-if="form.isCoupon == true">
							<el-table :data="couponList" style="width: 100%" class="ml20">
								<el-table-column prop="couponId" :label="$t('plus.coupon_id1')">
								</el-table-column>
								<el-table-column prop="name" :label="$t('plus.coupon_name1')">
								</el-table-column>
								<el-table-column :label="$t('plus.coupon_quantity')">
									<template #default="scope">
										<el-form-item :rules="[{  required: true,  message: '1-9'}, cprules]"
											:prop="'coupon.' + scope.$index + '.couponNum'">
											<el-input type="number" v-model="form.coupon[scope.$index].couponNum">
												<template #append>{{$t('plus.piece')}}</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column prop="address" :label="$t('plus.action')">
									<template #default="scope">
										<el-button type="primary" size="small" link @click="delcoupon(scope.row)"> {{$t('plus.delete')}} 

</el-button>
									</template>
								</el-table-column>
							</el-table>
							<el-button type="primary" @click="addCoupon('coup')" class="ml20 mt16 mb16"
								icon="Plus">{{$t('plus.add_coupon3')}}</el-button>
						</div>
						<el-form-item :label="$t('plus.give_points')">
							<el-input v-model="form.everSign" :placeholder="$t('plus.input_reward_points')" type="number" min="0">
								<template #append>{{$t('plus.gift_point')}}</template></el-input>
						</el-form-item>
					</div>
					<div>
						<span>{{$t('plus.incremental_reward')}}</span>
						<el-radio v-model="form.isIncrease" :label="true">{{$t('plus.enable')}}</el-radio>
						<el-radio v-model="form.isIncrease" :label="false">{{$t('plus.disable')}}</el-radio>
					</div>
					<div v-if="form.isIncrease" class="bg_coupon p-0-20 pt16 mt10">
						<el-form-item :label="$t('plus.incremental_start')" label-width="120px" prop="increase_reward">
							<div class="d-s-c">
								<div>
									<el-input v-model="form.increaseReward" :placeholder="$t('plus.input_incremental_points')"
										style="width: 180px" min="0" type="number"></el-input>
								</div>
								<span class="ml10">{{$t('plus.gift_point')}}</span>
							</div>
						</el-form-item>
						<el-form-item :label="$t('plus.day_prefix')" label-width="120px" prop="noIncrease">
							<div class="d-s-c">
								<div>
									<el-input v-model="form.noIncrease" :placeholder="$t('plus.input_stop_increment_day')" min="0"
										style="width: 180px" type="number"></el-input>
								</div>
								<span class="ml10">{{$t('plus.stop_increment_suffix')}}</span>
							</div>
						</el-form-item>
					</div>
				</el-form-item>
				<div class="mt10 mb10" style="margin-left: 100px">
					<span class="gray9">{{$t('plus.checkin_tip')}} 
</span>
				</div>
				<el-form-item :label="$t('plus.streak_checkin')" prop="everSign">
					<!-- <el-radio v-model="form.isOpen" :label="true">开启</el-radio>
          <el-radio v-model="form.isOpen" :label="false">关闭</el-radio> -->
				</el-form-item>
				<div class="open-sign">
					<span class="gray9">{{$t('plus.streak_reward_tip')}} 
</span>
				</div>
				<el-form-item label="">
					<div class="reward-list">
						<div class="reward-item pr " v-for="(item, reward_index) in form.rewardData"
							:key="reward_index">
							<el-button class="delete-reward" @click="deleteRewardClick(reward_index)" type="primary"
								size="small" link>{{$t('plus.delete')}}</el-button>
							<span class="ml10">{{$t('plus.streak_rule_label',{place1:reward_index + 1})}}</span>
							<el-form-item :label="$t('plus.streak_days')" :prop="'rewardData.' + reward_index + '.day'" :rules="rules.day">
								<div class="d-s-c">
									<div>
										<el-input v-model="item.day" :placeholder="$t('plus.input_streak_days')" class="max-w460"
											type="number" min="0"><template #prepend>{{$t('plus.streak')}}</template>
											<template #append>{{$t('plus.day_unit')}}</template></el-input>
									</div>
								</div>
							</el-form-item>
							<el-form-item label="">
								<div class="d-s-s d-c">
									<div class="ml20">
										<el-checkbox v-model="item.isCoupon">{{$t('plus.give_coupon_repeat')}}</el-checkbox>
										<el-checkbox v-model="item.isPoint">{{$t('plus.give_points')}}</el-checkbox>
									</div>
									<div style="width: 96%" v-if="item.isCoupon">
										<el-table :data="item.coupon" style="width: 100%" class="ml20">
											<el-table-column prop="couponId" :label="$t('plus.coupon_id1')">
											</el-table-column>
											<el-table-column prop="name" :label="$t('plus.coupon_name1')">
											</el-table-column>
											<el-table-column :label="$t('plus.coupon_quantity')">
												<template #default="scope">
													<el-form-item :rules="[{  required: true,  message: '1-9'}, cprules]"


 :prop="'coupon.' + scope.$index + '.couponNum'">
														<el-input type="number"
															v-model="item.coupon[scope.$index].couponNum">
															<template #append>{{$t('plus.piece')}}</template>
														</el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column prop="address" :label="$t('plus.action')">
												<template #default="scope">
													<el-button type="primary" size="small" link
														@click="delcoupons(reward_index, scope.$index)"> {{$t('plus.delete')}} 

</el-button>
												</template>
											</el-table-column>
										</el-table>
										<el-button type="primary" @click="addCoupon('coup_sum', reward_index)"
											class="ml20 mt16 mb16" icon="Plus">{{$t('plus.add_coupon3')}}</el-button>
									</div>
									<el-form-item :label="$t('plus.give_points')" v-if="item.isPoint">
										<el-input v-model="item.point" :placeholder="$t('plus.input_reward_points')" type="number" min="0"
											style="width: 200px">
											<template #append>{{$t('plus.gift_point')}}</template></el-input>
									</el-form-item>
								</div>
							</el-form-item>
						</div>
					</div>
					<el-button type="primary" size="small" icon="Plus" @click="addReward">{{$t('plus.add_streak_rule')}}</el-button>
				</el-form-item>
				<!--规则-->
				<el-form-item :label="$t('plus.rule_description')">
					<WangEditor style="width: 100%" :content="contents" @contens="contentm"
						@editorContent="getEditorContent"></WangEditor>
					<!-- <div class="edit_container">
            <Uediter
              :text="ueditor.text"
              :config="ueditor.config"
              ref="ue"
              @contentChange="contentChangeFunc"
            ></Uediter>
          </div> -->
				</el-form-item>
			</div>
			<!--提交-->
			<div class="common-button-wrapper">
				<el-button type="primary" size="small" @click="onSubmit" :disabled="loading">{{$t('plus.submit')}}</el-button>
			</div>
		</el-form>
		<GetCoupon v-if="open_add" :open_add="open_add" :use_type="20" :receiveType="2"
			@closeDialog="closeProductDialogFunc($event)">{{$t('plus.select_coupon_popup')}} 
</GetCoupon>
	</div>
</template>

<script>
import SignApi from "@/api/sign.js";
import GetCoupon from "@/components/coupon/GetCoupon.vue";
// import Uediter from "@/components/UE.vue";
import WangEditor from "@/components/wangEditor/index.vue";
export default {
  components: {
    /*编辑器*/
    // Uediter,
    WangEditor,
    GetCoupon
  },
  data() {
    /*判断额外奖励*/
    let validate_reward_data = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error($t("plus.add_extra_reward_tip")));
      } else {
        callback();
      }
    };

    /*连续签到天数*/
    let validate_day = (rule, value, callback) => {
      if (this.form.rewardData.length < 1) {
        callback();
      } else {
        if (value === "") {
          callback(new Error($t("plus.days_required_tip")));
        }
        callback();
      }
    };

    /*连续签到天数的积分数*/
    let validate_point = (rule, value, callback) => {
      if (value === "") {
        callback(new Error($t("plus.input_streak_points")));
      } else {
        callback();
      }
    };
    return {
      open_add: false,
      contents: "",
      /*富文本配置*/
      ueditor: {
        text: "",
        config: {
          initialFrameWidth: 400,
          initialFrameHeight: 500
        }
      },
      /*表单数据对象*/
      form: {
        isOpen: false,
        isIncrease: false,
        increaseReward: 0,
        noIncrease: 0,
        everSign: 0,
        rewardData: [],
        coupon: [],
        isCoupon: true,
        signType: 0
      },
      couponList: [],
      /*是否正在加载*/
      loading: true,
      loadings: false,
      /*验证规则*/
      rules: {
        /*每日签到*/
        everSign: [{
          required: true,
          message: $t("plus.daily_points_error"),
          trigger: "blur"
        }],
        /*第二天起递增*/
        increaseReward: [{
          required: true,
          message: $t("plus.input_incremental_points"),
          trigger: "blur"
        }],
        /*第几天不再递增*/
        noIncrease: [{
          required: true,
          message: $t("plus.input_stop_increment_day"),
          trigger: "blur"
        }],
        /*连续签到额外奖励*/
        rewardData: [{
          validator: validate_reward_data,
          required: true,
          trigger: "blur"
        }],
        /*连续签到*/
        day: [{
          validator: validate_day,
          required: true,
          trigger: "blur"
        }],
        /*连续签到积分数*/
        point: [{
          validator: validate_point,
          required: true,
          trigger: "blur"
        }]
      },
      couponName: ""
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    contentm(e) {
      this.contents = e;
    },
    getEditorContent(data) {
      console.log(data, "dtat");
      this.content = data;
    },
    addCoupon(name, index) {
      this.couponName = name;
      this.couponIndex = index;
      this.open_add = true;
    },
    /*关闭优惠券*/
    closeProductDialogFunc(e) {
      let self = this;
      self.open_add = e.openDialog;
      if (self.couponName == "coup") {
        if (e.type == "success") {
          if (self.form.coupon == null) {
            self.form.coupon = [];
          }
          console.log(self.form.coupon, "self.form.coupon");
          if (self.form.coupon.length < 1) {
            self.form.coupon.push({
              couponId: e.params.couponId,
              couponNum: 1
            });
            self.couponList.push({
              couponId: e.params.couponId,
              name: e.params.name,
              couponNum: 1
            });
          } else {
            let flag = true;
            self.form.coupon.forEach((item, index) => {
              if (item.couponId == e.params.couponId) {
                flag = false;
              }
            });
            if (flag) {
              self.form.coupon.push({
                couponId: e.params.couponId,
                couponNum: 1
              });
              self.couponList.push({
                couponId: e.params.couponId,
                name: e.params.name,
                couponNum: 1
              });
            } else {
              ElMessage.error($t("plus.do_not_repeat"));
            }
          }
          console.log(self.couponList);
        }
      } else if (self.couponName == "coup_sum") {
        if (e.type === "success") {
          // 确保 rewardData 中存在对应索引的 item
          const rewardItem = self.form.rewardData[self.couponIndex];
          if (rewardItem) {
            if (!Array.isArray(rewardItem.coupon)) {
              rewardItem.coupon = [];
            }
            const isDuplicate = rewardItem.coupon.some(coupon => coupon.couponId === e.params.couponId);
            if (!isDuplicate) {
              rewardItem.coupon.push({
                couponId: e.params.couponId,
                name: e.params.name,
                couponNum: 1
              });
            } else {
              ElMessage.error($t("plus.do_not_repeat"));
            }
          } else {
            ElMessage.error($t("plus.checkin_rule_not_found"));
          }
        }
      }
    },
    delcoupon(item) {
      let self = this;
      let n = self.couponList.indexOf(item);
      self.couponList.splice(n, 1);
      self.form.coupon.splice(n, 1);
    },
    delcoupons(index, couponIndex) {
      this.form.rewardData[index].coupon.splice(couponIndex, 1);
    },
    contentChangeFunc(e) {
      this.ueditor.text = e;
    },
    /*获取列表*/
    getData() {
      let self = this;
      self.loading = true;
      SignApi.getData().then(res => {
        self.loading = false;
        let val = res.data;
        if (val.isIncrease == true) {
          self.form.isIncrease = true;
        }
        if (val.isOpen == true) {
          self.form.isOpen = true;
          self.form.increaseReward = val.increaseReward;
          self.form.noIncrease = val.noIncrease;
          self.form.everSign = val.everSign;
          self.form.coupon = JSON.parse(JSON.stringify(val.coupon));
          self.couponList = val.coupon;
          self.form.signType = val.signType;
          self.contents = val.content;
          // self.ueditor.text = val.content;
          if (val.rewardData) {
            let len = val.rewardData.length;
            for (let i = 0; i < len; i++) {
              let item = val.rewardData[i];
              if (item.isCoupon == true) {
                item.isCoupon = true;
              } else {
                item.isCoupon = false;
              }
              if (item.isPoint == true) {
                item.isPoint = true;
              } else {
                item.isPoint = false;
              }
            }
            self.form.rewardData = val.rewardData;
          }
        }
        setTimeout(() => {
          self.loadings = true;
        }, 1000);
      }).catch(error => {
        self.loading = false;
      });
    },
    /*提交签到有礼*/
    onSubmit() {
      let self = this;
      let params = self.form;
      params.coupon = self.couponList;
      if (params.isOpen) {
        params.content = self.contents;
      }
      self.loading = true;
      console.log(params, "params");
      self.$refs.ruleForm.validate(valid => {
        if (valid) {
          SignApi.saveData(params, true).then(data => {
            ElMessage({
              message: $t("plus.save_success"),
              type: "success"
            });
            self.getData();
          }).catch(error => {
            self.loading = false;
          });
        }
      });
    },
    /*获取富文本编辑器的内容*/
    getContent: function () {
      return this.$refs.ue.getUEContent();
    },
    addReward() {
      let obj = {
        day: 0,
        isPoint: false,
        point: 0,
        isCoupon: false,
        coupon: []
      };
      this.form.rewardData.push(obj);
    },
    deleteRewardClick(e) {
      this.form.rewardData.splice(e, 1);
    }
  }
};
</script>

<style scoped="scoped">
.open-sign {
		margin-left: 100px;
		margin-bottom: 10px;
		margin-top: -20px;
	}

	.reward-list .reward-item {
		margin-bottom: 10px;
		padding: 10px 10px 0;
		background-color: rgba(246, 246, 246, 1);
	}

	.reward-list .delete-reward {
		position: absolute;
		top: 16px;
		right: 10px;
		cursor: pointer;
		z-index: 10;
	}

	.el-button--small.is-circle {
		padding: 4px;
	}

	.bg_coupon {
		background-color: rgba(246, 246, 246, 1);
		color: rgba(16, 16, 16, 1);
		font-size: 14px;
		padding: 10px 0;
	}
</style>

